import {createRouter, createWebHistory} from 'vue-router'
import {useAdminStore} from "@/stores/admin.js";
import {ElMessage} from "element-plus";

//本地已有页面
const localRouter = import.meta.glob('@/views/**/*.page.vue')
/**
 * 注册路由
 * @param menus 用户的菜单路由
 */
export const registerRouter = (menus) => {
    menus.forEach((menu) => {
        // 调用递归函数注册路由
        if (menu.children && menu.children.length > 0) {
            registerRouter(menu.children)
        } else {
            router.addRoute('main', {
                path: menu.path,
                name: menu.name,
                component: localRouter[`/src/views${menu.path}.page.vue`],
                meta: {
                    title: menu.name
                }
            })
        }
    })
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login.vue'),
            meta: {
                title: '登录'
            }
        },
        {
            path: '/',
            name: 'main',
            component: () => import('@/views/main/main.vue'),
        },
    ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const admin = useAdminStore();
    if (to.path === '/login') {
        next();
    } else {
        if (admin.admin.token) {
            next();
        } else {
            ElMessage.error('请先登录');
            next('/login');
        }
    }
});

// 全局后置守卫
router.afterEach((to, from) => {
    document.title = to?.meta.title || '默认标题';
});

export default router
